package com.intct.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @author gufg
 * @since 2025-08-21 14:26
 */
public class JedisUtil {

    private static JedisPool jedisPool;

    static {
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(10000);
        poolConfig.setMaxIdle(500);
        poolConfig.setMinIdle(100);
        jedisPool = new JedisPool(poolConfig, "cdh-node", 16379, 2000, "Test_090110");
    }

    public static Jedis getJedis() {
        return jedisPool.getResource();
    }

    public static void close(Jedis jedis) {

        if (jedis != null) {
            jedis.close();
        }
    }

    public static StatefulRedisConnection<String,String> getRedisAsyncConnection(){
        System.out.println("~~~获取异步操作Redis的客户端~~~");
        RedisURI uri = RedisURI.builder().withHost("cdh-node").withPort(16379).withPassword("Test_090110").build();

        RedisClient redisClient = RedisClient.create(uri);
        return redisClient.connect();
    }
    //关闭异步操作Redis的连接对象
    public static void closeRedisAsyncConnection(StatefulRedisConnection<String,String> asyncRedisConn){
        System.out.println("~~~关闭异步操作Redis的客户端~~~");
        if(asyncRedisConn != null && asyncRedisConn.isOpen()){
            asyncRedisConn.close();
        }
    }

    //以异步的方式从Redis中取数据
    public static JSONObject readDimAsync(StatefulRedisConnection<String,String> asyncRedisConn, String id){
        RedisAsyncCommands<String, String> asyncCommands = asyncRedisConn.async();
        try {
            String dimJsonStr = asyncCommands.get(id).get();
            if(StringUtils.isNotEmpty(dimJsonStr)){
                JSONObject dimJsonObj = JSON.parseObject(dimJsonStr);
                return dimJsonObj;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }
    //以异步的方式向Redis中放数据
    public static void writeDimAsync(StatefulRedisConnection<String,String> asyncRedisConn,
                                     String id,JSONObject dimJsonObj){
        RedisAsyncCommands<String, String> asyncCommands = asyncRedisConn.async();
        String key = id;
        asyncCommands.setex(key,24*60*60,dimJsonObj.toJSONString());

    }
}
